package com.dingup.provider.service.sys.impl;

import com.alibaba.fastjson.JSONArray;
import com.dingup.api.Util.RedisUtils;
import com.dingup.api.enums.DataPermissionEnum;
import com.dingup.api.model.sys.SysDept;
import com.dingup.api.model.sys.SysRole;
import com.dingup.provider.cache.PermissionCache;
import com.dingup.provider.mapper.SysDeptMapper;
import com.dingup.provider.service.permission.PermissionCacheService;
import com.dingup.provider.service.sys.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by wancheng on 2018/7/31.
 */
@Service
public class LoadUserPermissionServiceImpl implements LoadUserPermissionService {

    private static Logger logger = LoggerFactory.getLogger(LoadUserPermissionServiceImpl.class);

    private final Long ROOT_DEPTID = 0L;

    @Autowired
    SysDeptService sysDeptService;

    @Autowired
    SysRoleService sysRoleService;

    @Autowired
    SysUserService sysUserService;

    @Autowired
    SysDeptMapper sysDeptMapper;

    @Autowired
    SysPermissionService sysPermissionService;

    @Autowired
    PermissionCacheService permissionCacheService;

    @Override
    //@Async
    public void loadUserDataPermission(String userAccount) {
        String userId = RedisUtils.getInstance().getUserId(userAccount);
        List<SysDept> sysDepts = sysDeptService.getByUser(userId);
        //当前人的身份集合
        List<SysRole> roles = sysRoleService.getByUserId(userId);
        DataPermissionEnum userDataPermission = DataPermissionEnum.ONESELF;
        //获取最高的数据权限
        for (SysRole r : roles) {
            if (r.getDataPermission().intValue() < userDataPermission.getMark().intValue()) {
                userDataPermission = DataPermissionEnum.getEnum(r.getDataPermission());
            }
        }
        //登录人所拥有的权限部门
        List<Long> myDeptIds = new ArrayList<>();
        //登录人能够查看的人
        List<String> myUserIds = new ArrayList<>();
        for (SysDept d : sysDepts) {
            switch (userDataPermission){
                case ONESELF:
                    myDeptIds.add(d.getId());
                    myUserIds.add(userId);
                    break;
                case DEPTDOWN:
                    //当前部门及下属部门id集合
                    List<Long> deptIds = sysDeptService.getChildDeptIds(d.getId());
                    myDeptIds.addAll(deptIds);
                    List<String> userIds = sysUserService.getUserIdByDeptIds(deptIds);
                    myUserIds.addAll(userIds);
                    break;
                case DEPTUP:
                    //上级部门及其下属部门
                    List<Long> upDeptIds = sysDeptService.getChildDeptIds(d.getParentId());
                    myDeptIds.addAll(upDeptIds);
                    List<String> upUserIds = sysUserService.getUserIdByDeptIds(upDeptIds);
                    myUserIds.addAll(upUserIds);
                    break;
                case ALL:
                    List<Long> allDeptIds = sysDeptService.getChildDeptIds(ROOT_DEPTID);
                    myDeptIds.addAll(allDeptIds);
                    List<String> allUserIds = sysUserService.getUserIdByDeptIds(allDeptIds);
                    myUserIds.addAll(allUserIds);
                    break;
                default:
                    myDeptIds.add(d.getId());
                    myUserIds.add(userId);
                    break;
            }
        }
        myDeptIds = myDeptIds.stream().distinct().collect(Collectors.toList());
        myUserIds =  myUserIds.stream().distinct().collect(Collectors.toList());
        Map<String,Boolean> res = sysPermissionService.getRoleHasPermissionGroupTreeByUserId(userId);

        //加载进缓存中
        RedisUtils.getInstance().setDataPermission(userAccount,String.valueOf(userDataPermission.getMark()));
        RedisUtils.getInstance().setDataPermissionDept(userAccount,myDeptIds);
        RedisUtils.getInstance().setDataPermissionEmployee(userAccount,myUserIds);
        permissionCacheService.setPermission(userAccount,res);
        logger.info("用户:{},权限:PermissionCache={}",userAccount, JSONArray.toJSON(res));
        logger.info("用户:{},加载数据权限:deptIds={},userIds={}",userAccount, JSONArray.toJSON(myDeptIds), JSONArray.toJSON(myUserIds));
    }

    @Override
    public void loadOrganizationalStructure() {
        //获取所有部门
        List<SysDept> allDept = sysDeptMapper.getAll();
        Map<String,String> organizationalStructure = new HashMap<>();
        allDept.stream().forEach(
                d->{
                    organizationalStructure.put(String.valueOf(d.getId()),JSONArray.toJSONString(sysUserService.getUserIdByDeptIds(d.getId())));
                }
        );
        RedisUtils.getInstance().setOrganizationalStructure(organizationalStructure);
    }
}
